import React, { useState } from 'react'
import { View, Map, CoverView, CoverImage, Navigator } from '@tarojs/components'
import { HomeContainer } from './index.styled'
import Taro from '@tarojs/taro'

import center from '@/assets/resources/center.png'
import pin from '@/assets/resources/pin.png'
import buy from '@/assets/resources/buy.png'
import sell from '@/assets/resources/sell.png'

const { useReady } = Taro

let ctx = null

export default function index() {
  const [state, setState] = useState({
    longitude: 0,
    latitude: 0,
    markers: []
  })

  useReady(() => {
    ctx = Taro.createMapContext("map")

    Taro.getLocation({
      type: 'wgs84',
      success: (res) => {
        let { longitude, latitude } = res
        setState({
          ...state,
          longitude,
          latitude
        })
      }
    })

    const db = Taro.cloud.database()

    db.collection('minipet')
    .get({
      success: (res) => {
        // console.log(res)
        // res.data 是包含以上定义的两条记录的数组
        let markers = res.data.map((point) => {
          let { _id, latitude, longitude, type} = point
          return {
            id: _id,
            latitude,
            longitude,
            iconPath: type === 'buy' ? buy : sell,
            height: '80rpx',
            width: '80rpx'
          }
        })
        
        setState({
          ...state,
          markers
        })
      }
    })
  })

  return (
    <HomeContainer>
      <View class="home">
        <View class="map">
          <Map
            id="map"
            longitude={state.longitude}
            latitude={state.latitude}
            show-location
            markers={state.markers}
            bindmarkertap="handleMarkerTap"
          >
            <CoverView
              class="cover-view"
              onClick="handleCenterTap"
            >
              <CoverImage src={center}></CoverImage>
            </CoverView>
            <CoverView
              class="cover-view-pin"
            >
              <CoverImage src={pin}></CoverImage>
            </CoverView>
          </Map>
        </View>
        <View class="nav">
          <View class="publish">
            <Navigator open-type="navigate" url="/pages/publish/index">发布</Navigator>
          </View>
          <View class="search" onClick="handleSearchTap">
            搜索
          </View>
        </View>
      </View>
    </HomeContainer>
  )
}
